<?php

namespace App\Http\Controllers\Api;

use App\Address;
use App\Goods;
use App\GroupBuy;
use App\GroupBuyItem;
use App\GroupMaster;
use App\Http\Controllers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Jobs\CancelGroup;
use App\Jobs\CommissionJob;
use App\Jobs\GivingJob;
use App\Jobs\GroupBuyOverJob;
use App\Jobs\ReduceStock;
use App\Merchant;
use App\Order;
use App\Services\cityService;
use App\Services\MessageService;
use App\Services\PayService;
use App\Share;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PayController extends Controller
{
    use ApiResponse;

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $app = app('wechat.payment');
        $order = Order::where('order_number', $request->get('order_number'))->first();
        if (!$order){
            return $this->message_error("订单不存在");
        }
        if ($order->status != 0) {
            return $this->message_error("订单状态错误,无法支付");
        }
        if ($order->is_group_buy===1){
            $group_item=GroupBuyItem::where('order_number',$order->order_number)->first();
            if (Carbon::createFromTimeString($group_item->exp_time)->lt(Carbon::now())){
                return $this->message_error("拼团已经过期,请重新选择");
            }
        }
        //$order['pay_amount']
        $user=User::where('id',$order['uid'])->first();
        $result = $app->order->unify([
            'body' => '购买商品',
            'out_trade_no' => $order['order_number'],
            'total_fee' => floatval($order['pay_amount'])*100,
            'spbill_create_ip' => $request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $user['openid'],
        ]);
        Log::info("支付:",[$result]);
        if ($result['return_code']=="SUCCESS"){
            $jssdk=$app->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false); // 返回数组
            return $this->data($config);
        }else{
            return $this->message_error("支付失败，请稍后重试");
        }

    }
    public function notify(Request $request)
    {
        Log::info("支付回调:",[$request->all()]);
        $app = app('wechat.payment');
        $response = $app->handlePaidNotify(function($message, $fail)use ($app){
            Log::info("支付回调:",[$message]);
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = Order::where('order_number',$message['out_trade_no'])->first();

            if (!$order || $order->status==1) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
//
//            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////
//            $pay_query=$app->order->queryByOutTradeNumber($message['out_trade_no']);
//
//            if ($pay_query["trade_state"]=="SUCCESS"){
//                $payService=new PayService();
//                return $payService->success($message['out_trade_no'],$pay_query);
//            }else{
//                return true;
//            }
        });

        return $response; // return $response;
    }
    public function queryPay($order_number,Request $request)
    {
        $app = app('wechat.payment');
        $pay_query=$app->order->queryByOutTradeNumber($order_number);
        Log::info("订单查询:",[$pay_query]);
        if ($pay_query['return_code']==="SUCCESS"){

            if ($pay_query["trade_state"]=="SUCCESS"){
                $payService=new PayService();
                $success=$payService->success($order_number,$pay_query);
                if ($success){
                    return $this->message_success("支付成功");
                }
            }else{
                return $this->message_error("支付失败");
            }
        }
        return $this->data($pay_query);
    }

}
